import axios, { AxiosInstance, AxiosResponse } from 'axios'
import { message } from 'antd'


function setHttp() {
  // create an axios instance
  const service: AxiosInstance = axios.create({
    baseURL: (import.meta.env.VITE_APP_BASE_URL as string), // url = base url + request url
    withCredentials: true, // send cookies when cross-domain requests
    timeout: 30000, // request timeout
    headers: { 
      // 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
      Authorization: 'Bearer ' + localStorage.getItem('token')
    },
    // transformRequest: [(data: any) => qs.stringify({ reqData: JSON.stringify(data) })]
  
  })
  
  // request interceptor
  service.interceptors.request.use(
    (config) => {
      // more...
      config.headers.Authorization = 'Bearer ' + localStorage.getItem('token')
      return config
    },
    error => {
      // do something with request error
      return Promise.reject(error)
    }
  )
  
  
  // response interceptor
  service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
    */
  
    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    (response: AxiosResponse) => {
      const res = response.data
      // console.log('响应拦截：', res)
      if (res.code !== 200) {
        const res = response.data
        
        // 避免没有登录重复登录报异常接口
        if (res.code !== 401) {
          message.error(res.msg || res.message || res.msg.message || 'Error')
          return
        }

        // 401: 未登录;
        if (res.code === 401) {
          localStorage.removeItem('token')
          // 重新登录
          window.location.href = '/login'
          return
        }
  
        return Promise.reject(new Error(`${res.code}-${res.msg || res.message || res.msg.message}` || 'Error'))
      } else {
        return res
      }
    },
    error => {
      message.error(error.msg || error.message || error.msg.message || '接口异常')
      return Promise.reject(error)
    }
  )

  return service
}

const service = setHttp()

export default service
